package space.enemy;

import java.util.ArrayList;

import org.anddev.andengine.collision.BaseCollisionChecker;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.handler.collision.CollisionHandler;
import org.anddev.andengine.engine.handler.collision.ICollisionCallback;
import org.anddev.andengine.engine.handler.physics.PhysicsHandler;
import org.anddev.andengine.engine.handler.timer.ITimerCallback;
import org.anddev.andengine.engine.handler.timer.TimerHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.shape.IShape;
//import org.anddev.andengine.entity.scene.background.AutoParallaxBackground;
//import org.anddev.andengine.entity.scene.background.ColorBackground;
//import org.anddev.andengine.entity.scene.background.ParallaxBackground.ParallaxEntity;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.text.ChangeableText;
import org.anddev.andengine.entity.util.FPSLogger;



import org.anddev.andengine.opengl.font.Font;
import org.anddev.andengine.opengl.texture.Texture;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import org.anddev.andengine.sensor.accelerometer.AccelerometerData;
import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener;
import org.anddev.andengine.ui.activity.BaseGameActivity;

import space.enemy.ParallaxBackground.ParallaxEntity;

import android.graphics.Color;
import android.graphics.Typeface;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Debug;
import android.widget.Toast;


public class AnimatedSpritesExample extends BaseGameActivity implements SensorEventListener {
	// ===========================================================
	// Constants
	// ===========================================================

	public static final int CAMERA_WIDTH = 480;
	public static final int CAMERA_HEIGHT = 320;
	static final int BORDER_SIZE = 50;
	// ===========================================================
	// Fields
	// ===========================================================

	private Camera mCamera;

	private Texture mTexture;

	private TiledTextureRegion mSnapdragonTextureRegion;
	private TiledTextureRegion mHelicopterTextureRegion;
	private TiledTextureRegion mBananaTextureRegion;
	private TiledTextureRegion mFaceTextureRegion;
	private Texture mAutoParallaxBackgroundTexture;
	private TextureRegion mParallaxLayerFront;
	private Texture mTextureAlieni;
	private TiledTextureRegion mAlieniTextureRegion;
	private TextureRegion mParallaxLayerCloud;
	private PhysicsHandler physicsHandlerSpace;
	private PhysicsHandler physicsHandler;
	private int count=0;
	private float x;
	//private AnimatedSprite snapdragon;
    private int sX=100; // Sprite coordinates
	private SensorManager sensorManager;
	private ArrayList<SpaceEnemy> se;
	private EnemyManager enemyManager;
	private BulletManager bulletManager;
	private Texture mBulletTexture;
	private TextureRegion mBulletTextureRegion;
	private Texture mFireButtonTexture;
	private TextureRegion mFireButtonTextureRegion;
	private Shuttle shuttle;
	private Texture mTextureAlieniPar;
	private TiledTextureRegion mAlieniTextureRegionPar;
	//private EnemyStrong enemyStrong;
	private AutoParallaxBackground autoParallaxBackground;
	private ParallaxEntity parallaxLayerFront;
	private ParallaxEntity parallaxLayerCloud;
	private ChangeableText mText;
	private SpaceEnemy temp;
	private TiledTextureRegion mAlieniRottiTextureRegion;
	private SpaceEnemy2 temp2;
	private Texture mTextureAlieniRotti;
	protected boolean cancella;
	private Scene scene;
	

	// ===========================================================
	// Constructors
	// ===========================================================

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================

	@Override
	public Engine onLoadEngine() {
		this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
		return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
	}

	@Override
	public void onLoadResources() {
		
		/*this.mFontTexture = new Texture(256, 256, TextureOptions.BILINEAR);
  	  
		this.mFont = new Font(this.mFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 32, true, Color.GREEN);    */		
		
		
		//this.mTexture = new Texture(512, 512, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		//this.mSnapdragonTextureRegion = TextureRegionFactory.createTiledFromAsset(this.mTexture, this, "gfx/astronave step3-01.png", 0, 0, 4, 3);
		this.mTexture = new Texture(128, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);

		this.mSnapdragonTextureRegion = TextureRegionFactory.createTiledFromAsset(this.mTexture, this, "gfx/navicella.png", 0, 0, 2, 1);

		/*this.mAutoParallaxBackgroundTexture = new Texture( 1024,2048, TextureOptions.DEFAULT);
		this.mParallaxLayerFront = TextureRegionFactory.createFromAsset(this.mAutoParallaxBackgroundTexture, this, "gfx/fondo1-step3.png", 0, 470);
		
		this.mParallaxLayerCloud = TextureRegionFactory.createFromAsset(this.mAutoParallaxBackgroundTexture, this, "gfx/nuvole3.png", 0, 0);*/

		this.mTextureAlieni = new Texture(256, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mAlieniTextureRegion = TextureRegionFactory.createTiledFromAsset(this.mTextureAlieni, this, "gfx/alieni step 5-03.png", 0, 0, 4, 1);
		
		this.mTextureAlieniRotti = new Texture(256, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);		
		this.mAlieniRottiTextureRegion = TextureRegionFactory.createTiledFromAsset(this.mTextureAlieniRotti, this, "gfx/alieni_rotti.png", 0, 0, 4, 1);
		
		/*this.mTextureAlieniPar = new Texture(256, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mAlieniTextureRegionPar = TextureRegionFactory.createTiledFromAsset(this.mTextureAlieniPar, this, "gfx/alieni step 5-03.png", 0, 0, 4, 1);*/
		
		 this.mBulletTexture = new Texture(8, 16, TextureOptions.BILINEAR);
         this.mBulletTextureRegion = TextureRegionFactory.createFromAsset(this.mBulletTexture, this, "gfx/Bullet.png", 0, 0);
         
        
         this.mFireButtonTexture = new Texture(128, 128, TextureOptions.BILINEAR);
         this.mFireButtonTextureRegion = TextureRegionFactory.createFromAsset(this.mFireButtonTexture, this, "gfx/FireButton.png", 0, 0);
 		                        
        
		//this.mEngine.getTextureManager().loadTextures(this.mTexture,this.mTextureAlieni,this.mAutoParallaxBackgroundTexture,this.mBulletTexture);
		//this.mEngine.getTextureManager().loadTextures(this.mTexture,this.mTextureAlieni,this.mBulletTexture,this.mFireButtonTexture,this.mTextureAlieniPar);
		this.mEngine.getTextureManager().loadTextures(this.mTexture,this.mTextureAlieni,this.mBulletTexture,this.mFireButtonTexture,mTextureAlieniRotti);


	}

	@Override
	public Scene onLoadScene() {
		  sensorManager = (SensorManager) this.getSystemService(this.SENSOR_SERVICE);
	        sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), sensorManager.SENSOR_DELAY_GAME);
	 

		
		
		this.mEngine.registerUpdateHandler(new FPSLogger());

		scene = new Scene(1);
        scene.setBackground(new ColorBackground(0, 0, 0));

		/*autoParallaxBackground = new AutoParallaxBackground(0, 0, 0, 5);

		parallaxLayerFront = new AutoParallaxBackground.ParallaxEntity(0.0f,5.0f,false,true, new Sprite(0, 0, this.mParallaxLayerFront));
		parallaxLayerCloud = new AutoParallaxBackground.ParallaxEntity(0.0f,5.0f,false,true, new Sprite(0,  CAMERA_HEIGHT - this.mParallaxLayerCloud.getHeight(), this.mParallaxLayerCloud));
		
		autoParallaxBackground.addParallaxEntity(parallaxLayerFront);
		autoParallaxBackground.addParallaxEntity(parallaxLayerCloud);
		
		scene.setBackground(autoParallaxBackground);*/
		
        //shuttle = new Shuttle(150, 200, this.mSnapdragonTextureRegion,100,scene); 
        shuttle = new Shuttle(100, 70, this.mSnapdragonTextureRegion,100,scene); 
       temp = new SpaceEnemy(100,200, mAlieniTextureRegion,100,scene,10);
       
		bulletManager = new BulletManager(scene,shuttle,mBulletTextureRegion,mFireButtonTextureRegion);
		//enemyManager = new EnemyManager(bulletManager,scene,this.mAlieniTextureRegion,this.mEngine);

		//enemyStrong = new EnemyStrong(20,20, mAlieniTextureRegionPar,100,scene);
		
        mEngine.registerUpdateHandler(new CollisionHandler( new CollisionManager(), shuttle, enemyManager.getSpaceEnemyList() ));
        

		
		
		return scene;
	}

	protected void updateSpritePosition() {
		if ((x != 0)) {
            // Set the Boundary limits
            int tL = 0;
            int lL = 0;
            int rL = CAMERA_WIDTH - (int)this.shuttle.getWidth();
            int bL = CAMERA_HEIGHT - (int)this.shuttle.getHeight();
 
            // Calculate New X,Y Coordinates within Limits
            if (sX >= lL) sX += x; else sX = lL;
            if (sX <= rL) sX += x; else sX = rL;
           
 
            // Double Check That New X,Y Coordinates are within Limits
            if (sX < lL)      sX = lL;
            else if (sX > rL) sX = rL;
            
 
            this.shuttle.setPosition(sX, 200);
        }
	}

	@Override
	public void onLoadComplete() {
		//Debug.startMethodTracing("calc");
		//game loop
		this.mEngine.registerUpdateHandler(new IUpdateHandler() {
            public void onUpdate(float pSecondsElapsed) {
            	if(cancella){
            		System.out.println("registerUpdateHandler"+cancella);
            		mEngine.runOnUpdateThread(new Runnable() {
    	    			@Override
    	    			public void run() {
    	    				//cancello
    	    				mEngine.getScene().getLastChild().detachChild(temp);
    	    				cancella=false;	        				
    	    			}
    	    		});
            	    temp2 = new SpaceEnemy2(100,200, mAlieniRottiTextureRegion,100,scene,10);

            		temp2.setVisible(true);
            	}
            	if(enemyManager.getSpaceEnemyList().size()!=0){
	            	//enemyManager.update();
	            	bulletManager.update(shuttle.getX()+ shuttle.getWidth()/2,shuttle.getY());
	            	boolean moveDown=true;
	            	/*if(enemyStrong.getY()>CAMERA_HEIGHT - (int)shuttle.getHeight()){
	            		moveDown = false;
	            	}
	        		enemyStrong.update(moveDown);*/
	
	            	updateSpritePosition();
            	}
            	else{
					System.out.println("Vittoria!BUUUUUUUUUUUU");

            		//AnimatedSpritesExample.this.mEngine.unregisterUpdateHandler(this);
            		shuttle.stopAnimation();
            		//AnimatedSpritesExample.this.autoParallaxBackground.stop=true;
            	
            	}
            	if(!shuttle.isAlive()){
            		System.out.println("Hai Perso!Rosiconeeee");
            		shuttle.stopAnimation();
            		enemyManager.haltEnemies();
            		AnimatedSpritesExample.this.mEngine.unregisterUpdateHandler(this);					
            		


            	}
            }
 
            

			public void reset() {
            }
        });
		//loop che abilita il fire bullet ogni mezzo secondo
		this.mEngine.registerUpdateHandler( new TimerHandler(0.5f, new ITimerCallback() {
			
			@Override
			public void onTimePassed(TimerHandler pTimerHandler) {
				if ( shuttle.isAlive() == true ) {
					pTimerHandler.reset();
					bulletManager.enableShooting();
				}				
			}
			
		}));
		this.mEngine.registerUpdateHandler( new TimerHandler(10.0f, new ITimerCallback() {
			
			@Override
			public void onTimePassed(TimerHandler pTimerHandler) {
				System.out.println("onTimePassed"+pTimerHandler);
					pTimerHandler.reset();
					cancella = true;
								
			}
			
		}));
	}



	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		   switch (event.sensor.getType()) {
           case Sensor.TYPE_ACCELEROMETER:
               this.x = (int)event.values[1];
       		//System.out.println("ACCELLERAZIONE2:"+(int)event.values[1]);

               //accellerometerSpeedY = (int)event.values[0];
               break;
       }
   }
	static class CollisionManager implements ICollisionCallback {
    	
		@Override
		public boolean onCollision(IShape pCheckShape, IShape pTargetShape) {
			
			Shuttle ship = (Shuttle) pCheckShape;
			//System.out.println("COLLSION");
			if  ( ship.isAlive() && checkCollisions(pCheckShape,pTargetShape)) {
				

				ship.setLife(0);
				SpaceEnemy enemy = (SpaceEnemy) pTargetShape;
				//enemy.decreaseLife(SpaceEnemy.HEALTH);
				return true;//blocca il collision handler
			}
			
			return false; 
		

			
		}
				
		public static boolean checkCollisions(IShape pCheckShape, IShape pTargetShape) {
			return BaseCollisionChecker.checkAxisAlignedRectangleCollision( pCheckShape.getX(), pCheckShape.getY(), 
					pCheckShape.getX() + pCheckShape.getWidth(), pCheckShape.getY() + pCheckShape.getHeight(),
					pTargetShape.getX(), pTargetShape.getY(), 
					pTargetShape.getX() + pTargetShape.getWidth(), pTargetShape.getY() + pTargetShape.getHeight());
					
		}
    	
    }
	/*@Override
	public void onUnloadResources() {
	  Debug.stopMethodTracing();
	}*/

	
	
	}
		

